#include "Bitvector.h"

void initBitVector(int cantSectores)
{

	if (cantSectores % 8 ==0)
		cantBytes = cantSectores / 8;
	else
		cantBytes = cantSectores / 8 + 1;

	bitVector = malloc (cantBytes);

	memset(bitVector,0,cantBytes);

}

void setSector(unsigned int nroSector, int valor)
{

	  unsigned int pos,aux;
	    int offset;

	    pos = nroSector/8;
	    offset = nroSector - (pos*8);

	    if (valor==0)
	    {
	    //liberar sector
	    valor = 254;//11111110
	    //valor = valor << (7-offset);
	    aux=offset;
	    while(7-aux){
	        aux++;
	        valor = valor << 1;
	        valor = valor | 1;
	    }
	    bitVector[pos] = bitVector[pos] & valor;
	    }
	    else{
	        if (valor == 1)
	        {
	        //ocupar sector
	        valor = valor << (7-offset);
	        bitVector[pos] = bitVector[pos] | valor;
	        }
	        else
	        printf("EL VALOR INDICADO NO ES UN BIT.\n");
	        }
}

void liberarBitVector()
{
	//free(bitVector);
}



void sprintb(char* str, uint8_t *bytes, int size){
    int index;
    int str_offset=0;

    for(index=0; index<size; index++){
        sprintf(str+str_offset, BYTETOBINARYPATTERN, BYTETOBINARY( bytes[index] ));
        str_offset += 8;
    }

    str[str_offset] = '\0';
}

void bajarBitVector(void)
{

	uint8_t* cadenaBits;

	cadenaBits = malloc(cantBytes*8);
	uint8_t* copiaBit=malloc(cantBytes);
	memcpy(copiaBit,bitVector,cantBytes);

	sprintb(cadenaBits, copiaBit, cantBytes);
	freeSectors = fopen("/home/utn_so/free-sectors", "w");
	fprintf(freeSectors, "%s", cadenaBits);
	fclose(freeSectors);
	free(cadenaBits);
	free(copiaBit);

}




